// JavaScript Document
var functionalitiesList;
var widgetInfo;
var returnPage;


function FunctionalitiesPageBuilder () {
	PageBuilder.call(this);
}

FunctionalitiesPageBuilder.prototype = new FunctionalitiesPageBuilder();

FunctionalitiesPageBuilder.prototype.constructor = FunctionalitiesPageBuilder;

FunctionalitiesPageBuilder.prototype.build = function () {
	$("#functionalities_label").html(getDisplayString("functionalities_title"));
	$("#done_button").html(getDisplayString("donebutton_caption"));
	$("#not_logged_in_Message").html(getDisplayString("not_signed_in"));
}


$(document).ready(function(){
	setLogin();
	buildPage(new FunctionalitiesPageBuilder());
	registerResponderForSignal ( "receivedWidgetInfo", displayWidgetInfo );
	registerResponderForSignal ( "receivedFunctionalities", showFunctionalities);
	widget_id = getQueryVariable("widgetId");
	returnPage = getQueryVariable("returnPage");
	if ( widget_id ) {
		getWidgetInfo ( widget_id );
	}
	

	
	$("#searchText").on('keydown', function(e) {
		if ( e.which == 13 ) {
			e.preventDefault();
			searchStore();
		}
	});
	//$("#functionalities_group_list").buttonset();
	//getFunctionalities(0);
	
});

function goToWidgetView()
{
	if ( returnPage == "user" ) {
		window.location = "user.html";
	}
	else {
		window.location = "widget_view.html?widgetId="+widgetInfo.widgetProfile.id;
	}
}

function changeGroup(sel) {
	var value = sel.options[sel.selectedIndex].value;
	getFunctionalities(value);
}


function displayWidgetInfo(wInfo ) {
	widgetInfo = wInfo;
	var name = widgetInfo.widgetProfile.name;
	var icon = widgetInfo.widgetProfile.icon;
	if ( !icon ) {
		icon = "img/default_widget_icon.png";
	}
	
	var disp = '<img src="'+icon+'" class="wf_icon" alt="'+name+'"/>&nbsp;<span class="wf_title">'+name+'</span>';
	$("#widgetInfo").html(disp);
	var wfuncs = widgetInfo.widgetProfile.functionalities;
	for ( var i=0; i < wfuncs.length; i++ ) {
		var f = wfuncs[i];
		appendFunctionalityBlock ( f );
	}
	getFunctionalities(0);
	
}

function showFunctionalities (functionalities) {
	functionalitiesList = functionalities; // store a local copy
	var widgetFunctionalities = widgetInfo.widgetProfile.functionalities;
	if ( !widgetFunctionalities ) {
		widgetFunctionalities = new Array();
	}
	for ( var i = 0; i < functionalities.length; i++ ) {
		var f = functionalities[i];
		var selected = false;
		// find if this functionality if already set in the widget
		for ( var j = 0;j < widgetFunctionalities.length; j++ ) {
			var wf = widgetFunctionalities[j];
			if ( wf.uri == f.uri ) {
				selected = true;
				break;
			}
		}
		var s = '<div class="func_check"><input type="checkbox" id="check'+i+'" value="'+f.uri+'"';
		if ( selected ) {
			s += 'checked';
		}
		s+= ' onclick="toggleFunctionality(\'check'+i+'\')"/>&nbsp;<label for="check'+i+'">'+f.name+'</label></div>';
		$("#functionalities_group_list").append(s);
		var checkBoxId = "#check"+i;
		//$(checkBoxId).button();
		//$(checkBoxId).prop('checked', selected);
		//$(checkBoxId).click(function(){
		//	var uri = $(this).val();
		//	if ( !$(this).prop("checked")) {
		//		removeFunctionalityFromWidget ( uri );
		//	}
		//	else {
		//		findFunctionalityAndAddToWidget( uri );
		//	}
		//});
	}
}

function toggleFunctionality(checkid){
	var uri = $("#"+checkid).val();
	if (!$("#"+checkid).prop("checked")) {
		removeFunctionalityFromWidget(uri);
	}
	else {
		findFunctionalityAndAddToWidget(uri);
	}
}

function removeFunctionalityFromWidget ( uri ) {
	var u = getUser();
	if ( u == null ) {
		alert ("You must be logged in to removed functionalities from a widget");
		return;
	}
	var f = findFunctionality ( uri );
	if ( f ) {
		var restCall = store_rest_url+"/functionalities/edit/"+widgetInfo.widgetProfile.id+"/"+f.id;
		var u = getUser ();
		if ( u == null ) {
			alert ( "You must be logged in to perform this action");
			return;
		}
		$.ajax({
			type: "DELETE",
			url: restCall,
			beforeSend: function(xhr) {
				var authString = getBase64Authentication();
				xhr.setRequestHeader("Authorization", "Basic "+authString);
			},
			dataType: "text",
			success: functionalityRemoved
		});
		//removeFunctionalityFromWidgetInfo ( uri );
		removeBlock ( f );
	}
}


function functionalityRemoved (jsonString ) {
	sendSignal ( "functionalityRemoved" );
}


function findFunctionality ( uri ) {
	for ( var i=0; i<functionalitiesList.length; i++ ) {
		var f = functionalitiesList[i];
		if ( f.uri == uri ) {
			return f;
		}
	}
	return null;
}


function findFunctionalityAndAddToWidget( uri ) {
	var f = findFunctionality ( uri );
	if ( f ) {
		addFunctionalityToWidget( f);
	}
}


function addFunctionalityToWidget ( f ) {
	var restCall = store_rest_url+"/functionalities/edit";
	var u = getUser();
	if ( u == null ) {
		alert ( "You must be logged in to do this action" );
		return;
	}
	var wid = widgetInfo.widgetProfile.id;
	var fdata = {username:u.username, widget_id:wid, functionality_id:f.id, relevance:50};
	
	$.ajax({
		type:"POST",
		url:restCall,
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		data:fdata,
		dataType:"text",
		success: functionalitySet
	});
}

function updateRelevance ( f, relevance ) {
	// put call for this not accessible through proxy!
	// fudge this
	
	var restCall = store_rest_url+"/functionalities/edit";
	if ( getUser() == null ) {
		alert ( "You must be logged in to do this" );
		return;
	}
	var fdata = {username:getUser().username,widget_id:widgetInfo.widgetProfile.id,functionality_id:f.id, relevance:relevance};
	$.ajax({
		type:"POST",
		url:restCall,
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		data: fdata,
		dataType:"text",
	});
		
}



function functionalitySet ( jsonString ) {
	var functionality = $.parseJSON(jsonString);
	tempAddFunctionalityToWidgetInfo ( functionality );
	appendFunctionalityBlock ( functionality );
}


function tempAddFunctionalityToWidgetInfo ( f ) {
	if ( widgetInfo.widgetProfile.functionalities == null ) {
		widgetInfo.widgetProfile.functionalities = new Array();
	}
	widgetInfo.widgetProfile.functionalities.push(f);
}


function appendFunctionalityBlock ( f ) {
	// get the number of items already there to set the vertical position
	var fcount = $("#widget_functionality_box > div").size();

	var block = '<div id="functionality'+f.id+'" class="functionality_block">'+f.name+' <span id="pos'+f.id+'">'+f.relevance+'%</span></div>';

	
	$("#widget_functionality_box").append(block);
		
	var pos = $("#pos"+f.id);
	var box_offset = $("#widget_functionality_box").offset().left;
	var box_width = $("#widget_functionality_box").width();
	var f_box_width = $("#functionality"+f.id).width();
	var percent_factor = 100/(box_width - f_box_width);
	
	var f_box = "#functionality"+f.id
	$(f_box).draggable({ 
		containment: "#widget_functionality_box", 
		scroll: false,
		drag: function () {
			var p = $(this).position();
			var relative_l = p.left - box_offset;
			pos.html(Math.round(relative_l * percent_factor));
		},
		stop: function() {
			var p = $(this).position();
			var relative_l = p.left - box_offset;
			var relevance = Math.round(relative_l * percent_factor);
			updateRelevance ( f, relevance );
		}
	});
	
			// set it's relative position
	var x = f.relevance/percent_factor;
	var h = 30;
	var y = 8+(fcount * (h+16));
	$(f_box).position({
		my: "left top",
		at: "left top",
		of: "#widget_functionality_box",
		offset: ""+x+" "+y+""
	});
}


function removeBlock ( f ) {
	$("#widget_functionality_box").children("#functionality"+f.id).remove();
}
	

		